package com.letter.otools.day.util;

import android.content.Context;
import android.net.Uri;
import android.util.Log;


import com.blankj.utilcode.util.FileIOUtils;
import com.blankj.utilcode.util.FileUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * 解决部分手机从相册选择图片报权限不够的问题
 */
public class FkhUriFixUtils {

    //保存缓存文件的路径
    public final static String cacheFixFolderName = "/fkhFileFixCache";

    //将图片拷贝到内部缓存
    public static File copyUri2Cache(Context context, String cacheFolder, Uri uri, String fileExt) {
        InputStream is = null;
        try {
            is = context.getContentResolver().openInputStream(uri);
            String fileName = System.currentTimeMillis() + "." + fileExt;//FileUtils.getFileName(orgFilePath);
//            if (StringUtils.isEmpty(fileName)) {
//                fileName = System.currentTimeMillis() + FileUtils.getFileName(fileName);
//            }
            File file = new File(cacheFolder + "/" + fileName);
            if (FileUtils.createOrExistsFile(file)) {
                FileIOUtils.writeFileFromIS(file, is);
            }

            Log.e("UriUtils", file.getAbsolutePath());
            return file;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //将会转为APP缓存文件路径
    public static String fixFilePath(Context context, Uri fileOrgUri, String fileExt) {
        //将相册文件缓存到本地
        String folder = context.getCacheDir().getAbsolutePath() + cacheFixFolderName;
        File cachleFile = copyUri2Cache(context, folder, fileOrgUri, fileExt);
        //使用缓存文件的路径
        assert cachleFile != null;
        return cachleFile.getAbsolutePath();
    }

    //打开APP就清除掉缓存
    public static void clearCache(Context context) {
        String folder = context.getCacheDir().getAbsolutePath() + cacheFixFolderName;
        FileUtils.deleteFilesInDir(folder);
    }
}
